package tech.aistar.day11;

import java.util.concurrent.TimeUnit;

/**
 * 本类用来演示: 死锁
 *
 * @author: success
 * @date: 2022/8/2 2:17 下午
 */
public class DeadDemo {
    //每个对象拥有独立的一把锁
    public static Object obj1 = new Object();//临界资源
    public static Object obj2 = new Object();//临界资源
}
class D1 extends Thread{
    DeadDemo deadDemo = new DeadDemo();

    @Override
    public void run() {
        synchronized (deadDemo.obj1){//不同的对象拥有的是独立的锁
            System.out.println("==11==");

            //让d2线程有足够的时间能够获取到obj2对象锁
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //如果希望继续执行,必须要先获取到obj2对象锁
            synchronized (deadDemo.obj2){
                System.out.println("==22==");
            }
        }
    }
}

class D2 extends Thread{
    DeadDemo deadDemo = new DeadDemo();

    @Override
    public void run() {
        synchronized (deadDemo.obj2){
            System.out.println("==33===");

            //为了让d1能够有足够的时间拿到obj1对象锁
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            //如果希望继续执行,必须要先获取到obj1对象锁
            synchronized (deadDemo.obj1){
                System.out.println("==44==");
            }
        }
    }
}
class DeadDemoTest{
    public static void main(String[] args) {
        Thread d1 = new D1();
        Thread d2 = new D2();

        d1.start();

        d2.start();
    }
}